package com.ruoyi.waterManagement.controller;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.MapUtil;
import com.ruoyi.common.core.domain.business.waterManagement.RelZQ;
import com.ruoyi.waterManagement.service.IRelZQService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import static com.ruoyi.waterManagement.util.importFileTest.getCellValue;

/**
 * 水位流量关系对照Controller
 *
 * @author hwd
 * @date 2023-02-23
 */
@RestController
@RequestMapping("/RelZQ")
public class RelZQController extends BaseController
{
    @Autowired
    private IRelZQService relZQService;


    /**
     * 根据测站代码查询所属的曲线名称
     * @param statCd
     * @return
     */
    @GetMapping(value = "/selCurvNmByStatCd")
    public AjaxResult selCurvNmByStatCd(String statCd)
    {
        List<RelZQ> relZQS= relZQService.selCurvNmByStatCd(statCd);
        return AjaxResult.success(relZQS);
    }

    /**
     * 根据测站代码和曲线名称查询换算表
     * @param
     * @return
     */
    @GetMapping(value = "/selectRelZQListByStatCdAndCurvNm")
    public AjaxResult selectRelZQListByStatCdAndCurvNm( RelZQ relZQ1)
    {
        List<RelZQ> relZQS= relZQService.selectRelZQList(relZQ1).stream().sorted(Comparator.comparing(RelZQ::getPtNo,Comparator.comparingInt(Integer::parseInt))).collect(Collectors.toList());
        Map<Integer, Map<Integer, BigDecimal>> relZQListMap= relZQService.selectRelZQListMap(relZQS);
        Set<Integer> keySet = relZQListMap.keySet();
        Iterator<Integer> iter = keySet.iterator();
        Map<Integer,List<BigDecimal>> integerListMap=new HashMap<>();

        while (iter.hasNext()) {
            List<BigDecimal> bigDecimals=new ArrayList<>();
            Integer key = iter.next();
            Map<Integer, BigDecimal> s =relZQListMap.get(key);
            Set<Integer> keySets = s.keySet();
            Iterator<Integer> iters = keySets.iterator();
            while (iters.hasNext()) {
                Integer keys = iters.next();
                bigDecimals.add(s.get(keys));
            }
            integerListMap.put(key,bigDecimals);
        }
        //0,[0,2,5,3] 10,20
        Map<Integer,List<BigDecimal>> listMap= MapUtil.sortMapByKey(integerListMap);
        Set<Integer> keySets = listMap.keySet();
        Iterator<Integer> iters = keySets.iterator();
        List<List<BigDecimal>> listlist = new ArrayList<>();
        //list中list
        while (iters.hasNext()) {
            Integer keys = iters.next();
            List<BigDecimal> lists = new ArrayList<>();
            lists.add(new BigDecimal(keys));
            lists.addAll(listMap.get(keys));
            listlist.add(lists);
        }

        return AjaxResult.success(listlist);
    }

    /**
     *启动关闭关系曲线函数
     * @param
     * @return
     */

    @Log(title = "启动关闭关系曲线函数", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/updateRelZQEnabType")
    public AjaxResult updateRelZQEnabType(RelZQ relZQ)
    {
        int s= relZQService.updateRelZQEnabType(relZQ);
        return toAjax(s);
    }

    /**
     *查询测站水位流量关系曲线表 默认先查启动时间最新的
     * @param statCd
     * @param curvNm
     * @return
     */
    @GetMapping(value = "/selQXByStatCdAndCurvNm")
    public AjaxResult selQXByStatCdAndCurvNm(String statCd,String curvNm)
    {

        RelZQ relZQ= relZQService.selQXByStatCdAndCurvNm(statCd,curvNm);
        return AjaxResult.success(relZQ);
    }
    /**
     * 查询水位流量关系对照列表
     */
    @RequiresPermissions("waterManagement:RelZQ:list")
    @GetMapping("/list")
    public TableDataInfo list(RelZQ relZQ)
    {
        startPage();
        List<RelZQ> list = relZQService.selectRelZQList(relZQ);
        return getDataTable(list);
    }

    /**
     * 导出水位流量关系对照列表
     */
    @RequiresPermissions("waterManagement:RelZQ:export")
    @Log(title = "水位流量关系对照", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RelZQ relZQ)
    {
        List<RelZQ> list = relZQService.selectRelZQList(relZQ);
        ExcelUtil<RelZQ> util = new ExcelUtil<RelZQ>(RelZQ.class);
        util.exportExcel(response, list, "水位流量关系对照数据");
    }

    /**
     * 获取水位流量关系对照详细信息
     */
    @RequiresPermissions("waterManagement:RelZQ:query")
    @GetMapping(value = "/{statCd}")
    public AjaxResult getInfo(@PathVariable("statCd") String statCd)
    {
        return success(relZQService.selectRelZQByStatCd(statCd));
    }

    /**
     * 新增水位流量关系对照
     */
    @RequiresPermissions("waterManagement:RelZQ:add")
    @Log(title = "水位流量关系对照", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RelZQ relZQ)
    {
        return toAjax(relZQService.insertRelZQ(relZQ));
    }

    /**
     * 修改水位流量关系对照
     */
    @RequiresPermissions("waterManagement:RelZQ:edit")
    @Log(title = "水位流量关系对照", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RelZQ relZQ)
    {
        return toAjax(relZQService.updateRelZQ(relZQ));
    }

    /**
     * 删除水位流量关系对照
     */
    @RequiresPermissions("waterManagement:RelZQ:remove")
    @Log(title = "水位流量关系对照", businessType = BusinessType.DELETE)
    @DeleteMapping("/{statCds}")
    public AjaxResult remove(@PathVariable String[] statCds)
    {
        return toAjax(relZQService.deleteRelZQByStatCds(statCds));
    }

    /**
     * 关系曲线函数下载模板
     * @param response
     * @throws IOException
     */

    @Log(title = "关系曲线函数模板", businessType = BusinessType.EXPORT)
    @PostMapping("/importTemplate")
    public void importTemplateOne(HttpServletResponse response) throws IOException {
//        ExcelUtil<WaterLevelRelationCurveMaintainTemplateOne> util = new ExcelUtil<WaterLevelRelationCurveMaintainTemplateOne>(WaterLevelRelationCurveMaintainTemplateOne.class);
//        util.importTemplateExcel(response, "关系曲线率定数据第一种模板");
        relZQService.exportExcel(response);
    }

    /**
     * 关系曲线函数导入
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "关系曲线函数导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        Boolean flag =false;
        // 解析表格，需要从 MultipartFart 获取到输入流 InputStream。
        InputStream inputStream = null;
        try {
            List<RelZQ> relZQList = new ArrayList<>();
            String flieName = file.getResource().getFilename();
            boolean falg =false;
            if (flieName.endsWith("xlsx")) {
                inputStream =file.getInputStream();
                BufferedInputStream in = new BufferedInputStream(file.getInputStream());
//            POIFSFileSystem fs = new POIFSFileSystem(in);
                XSSFWorkbook wb = new XSSFWorkbook(in);
                XSSFSheet st = wb.getSheetAt(0);
                int i = 0;
                XSSFRow stRow = st.getRow(0);
                String statCd = getCellValue(stRow.getCell(1));//读取测站代码
                String curvNm =getCellValue(stRow.getCell(3));//曲线名称
                if (statCd.equals("") &&  curvNm.equals("")){
                    return AjaxResult.error("测站代码或曲线名称不存在");
                }
                //先检验曲线名称是否存在，如果存在则返回
                QueryWrapper<RelZQ> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(RelZQ::getStatCd, statCd).eq(RelZQ::getCurvNm, curvNm);
                int nm = relZQService.count(queryWrapper);
                if (nm > 0) {
                    return AjaxResult.error("新增曲线'" +curvNm + "'失败，曲线名称已存在");
                }
                for (int rowIndex = 3; rowIndex <= st.getLastRowNum(); rowIndex++) {
                    if (falg){
                        break;
                    }
                    XSSFRow row = st.getRow(rowIndex);
                    BigDecimal sw = new BigDecimal(getCellValue(row.getCell(0)));
                    for (int cellIndex = 1; cellIndex < row.getLastCellNum()-1; cellIndex++) {
//                System.out.println("第" + rowIndex + "行;" + "第" + cellIndex + "列" + row.getCell(cellIndex));
                        //水位 对应流量
                        i++;
                        if ( isEmptyCell(row.getCell(cellIndex)) ){ //判断单个单元格是否为空
                            falg=true;
                            continue;
                        }
                        BigDecimal sw2 = new BigDecimal((cellIndex - 1) + "").add(sw);
                        BigDecimal ll = new BigDecimal(getCellValue(row.getCell(cellIndex)));
                        if (ll.compareTo(new BigDecimal(0))==0 || sw2.compareTo(new BigDecimal(0))==0 ){
                            continue;
                        }
                        RelZQ relZQ = new RelZQ();
                        relZQ.setPtNo(i+"");
                        relZQ.setStatCd(statCd);
                        relZQ.setEnabType(1);
                        relZQ.setCurLevel(sw2.divide(new BigDecimal("100"),2,BigDecimal.ROUND_HALF_UP));
                        relZQ.setCurFlow(ll);
                        relZQ.setEnabTm(new Date());
                        relZQ.setSiltDepth(new BigDecimal(0));
                        relZQ.setNt("");
                        relZQ.setCurvNm(curvNm);
                        relZQList.add(relZQ);
                    }
                }
            }
            if (flieName.endsWith("xls")) {
                BufferedInputStream in = new BufferedInputStream(file.getInputStream());
                POIFSFileSystem fs = new POIFSFileSystem(in);
                HSSFWorkbook wb = new HSSFWorkbook(fs);
                HSSFSheet st = wb.getSheetAt(0);
                int i = 0;
                HSSFRow stRow = st.getRow(0);
                String statCd = getCellValue(stRow.getCell(1));//读取测站代码
                String curvNm =getCellValue(stRow.getCell(3));//曲线名称
                if (statCd.equals("") &&  curvNm.equals("")){
                    return AjaxResult.error("测站代码或曲线名称不存在");
                }
                //先检验曲线名称是否存在，如果存在则返回
                QueryWrapper<RelZQ> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(RelZQ::getStatCd, statCd).eq(RelZQ::getCurvNm, curvNm);
                int nm = relZQService.count(queryWrapper);
                if (nm > 0) {
                    return AjaxResult.error("新增曲线'" +curvNm + "'失败，曲线名称已存在");
                }

                for (int rowIndex = 3; rowIndex <= st.getLastRowNum(); rowIndex++) {
                    if (falg){
                        break;
                    }
                    HSSFRow row = st.getRow(rowIndex);
                    BigDecimal sw = new BigDecimal(getCellValue(row.getCell(0)));
                    for (int cellIndex = 1; cellIndex < row.getLastCellNum()-1; cellIndex++) {
//                System.out.println("第" + rowIndex + "行;" + "第" + cellIndex + "列" + row.getCell(cellIndex));
                        //水位 对应流量
                        i++;
                        BigDecimal sw2 = new BigDecimal((cellIndex - 1) + "").add(sw);
                        BigDecimal ll = new BigDecimal(getCellValue(row.getCell(cellIndex)));
                        if (ll.compareTo(new BigDecimal(0))==0 || sw2.compareTo(new BigDecimal(0))==0 ){
                            break;
                        }
                        if ( isEmptyCell(row.getCell(cellIndex)) ){ //判断单个单元格是否为空
                            falg=true;
                            break;
                        }
                        RelZQ relZQ = new RelZQ();
                        relZQ.setPtNo(i+"");
                        relZQ.setStatCd(statCd);
                        relZQ.setEnabType(1);
                        relZQ.setCurLevel(sw2.divide(new BigDecimal("100"),2,BigDecimal.ROUND_HALF_UP));
                        relZQ.setCurFlow(ll);
                        relZQ.setEnabTm(new Date());
                        relZQ.setSiltDepth(new BigDecimal(0));
                        relZQ.setNt("");
                        relZQ.setCurvNm(curvNm);
                        relZQList.add(relZQ);
                    }
                }
            }
            if (relZQList.size()>0){
                flag = relZQService.importRelZQList(relZQList);
            }else {
                return AjaxResult.error("插入数据为空");
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return AjaxResult.error(e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return AjaxResult.success(flag);
    }


    //判断单个单元格是否为空
    public static boolean isEmptyCell(Cell cell){
        if(cell==null||cell.getCellType().equals(CellType.BLANK)){
            return true;
        }
        return false;
    }
//
//    /**
//     * 插入测试水位流量关系数据
//     */
//
//    @Log(title = "水位流量关系对照", businessType = BusinessType.DELETE)
//    @GetMapping("/insertRzQ")
//    public void testRzQ()
//    {
//        RelZQ relZQ= new RelZQ();
//        relZQ.setStatCd("STA6543220001");
//        List<RelZQ> relZQList =relZQService.selectRelZQList(relZQ);
//        String[] statCds ={
//                "STA6543220002" ,
//                "STA6543220003" ,
//                "STA6543220004" ,
//                "STA6543220005" ,
//                "STA6543220006" ,
//                "STA6543220007" ,
//                "STA6543220008" ,
//                "STA6543220009" ,
//                "STA6543220010" ,
//                "STA6543220011" ,
//                "STA6543220012" ,
//                "STA6543220013" ,
//                "STA6543220014" ,
//                "STA6543220015" ,
//                "STA6543220016" ,
//                "STA6543220017" ,
//                "STA6543220018" ,
//                "STA6543220019" ,
//                "STA6543220020" ,
//                "STA6543220021" ,
//                "STA6543220022" ,
//                "STA6543220023" ,
//                "STA6543220024" ,
//                "STA6543220025" ,
//                "STA6543220026" ,
//                "STA6543220027" ,
//                "STA6543220028" ,
//                "STA6543220029" ,
//                "STA6543220030" ,
//                "STA6543220031" ,
//                "STA6543220032" ,
//                "STA6543220033" ,
//                "STA6543220034" ,
//                "STA6543220035" ,
//                "STA6543220036" ,
//                "STA6543220037" ,
//                "STA6543220038" ,
//                "STA6543220039" ,
//                "STA6543220040" ,
//                "STA6543220041" ,
//                "STA6543220042" ,
//                "STA6543220043" ,
//                "STA6543220044" ,
//                "STA6543220045" ,
//                "STA6543220046" ,
//                "STA6543220047" ,
//                "STA6543220048" ,
//                "STA6543220049" ,
//                "STA6543220050" ,
//                "STA6543220051" ,
//                "STA6543220052" ,
//                "STA6543220053" ,
//                "STA6543220054" ,
//                "STA6543220055" ,
//                "STA6543220056" ,
//                "STA6543220057" ,
//                "STA6543220058" ,
//                "STA6543220059" ,
//                "STA6543220060" ,
//                "STA6543220061" ,
//                "STA6543220062" ,
//                "STA6543220063" ,
//                "STA6543220064" ,
//                "STA6543220065" ,
//                "STA6543220066" ,
//                "STA6543220067" ,
//                "STA6543220068" ,
//                "STA6543220069" ,
//                "STA6543220070" ,
//                "STA6543220071" ,
//                "STA6543220072" ,
//                "STA6543220073" ,
//                "STA6543220074" ,
//                "STA6543220075" ,
//                "STA6543220076" ,
//                "STA6543220077" ,
//                "STA6543220078" ,
//                "STA6543220079" ,
//                "STA6543220080" ,
//                "STA6543220081" ,
//                "STA6543220082" ,
//                "STA6543220083" ,
//                "STA6543220084" ,
//                "STA6543220085" ,
//                "STA6543220086" ,
//                "STA6543220087" ,
//                "STA6543220088" ,
//                "STA6543220089" ,
//                "STA6543220090" ,
//                "STA6543220091" ,
//                "STA6543220092" ,
//                "STA6543220093" ,
//                "STA6543220094" ,
//                "STA6543220095" ,
//                "STA6543220096" ,
//                "STA6543220097" ,
//                "STA6543220098" ,
//                "STA6543220099" ,
//                "STA6543220100" ,
//                "STA6543220101" ,
//                "STA6543220102" ,
//                "STA6543220103" ,
//                "STA6543220104" ,
//                "STA6543220105" ,
//                "STA6543220106" ,
//                "STA6543220107" ,
//                "STA6543220108" ,
//                "STA6543220109" ,
//                "STA6543220110" ,
//                "STA6543220111" ,
//                "STA6543220112" ,
//                "STA6543220113" ,
//                "STA6543220114" ,
//                "STA6543220115" ,
//                "STA6543220116" ,
//                "STA6543220117" ,
//                "STA6543220118" ,
//                "STA6543220119" ,
//                "STA6543220120" ,
//                "STA6543220121" ,
//                "STA6543220122" ,
//                "STA6543220123" ,
//                "STA6543220124" ,
//                "STA6543220125" ,
//                "STA6543220126"};
//        for (String stcd:statCds
//             ) {
//            for (RelZQ r:relZQList
//                 ) {
//                r.setStatCd(stcd);
//                r.setCurvNm(relZQService.selectStatCd(stcd));
//                relZQService.insertRelZQ(r);
//            }
//        }
//
//
//
//    }

    public static void main(String[] args) {

        String[] statCds =new String[]{
                "STA6543220002" ,
                "STA6543220003" ,
                "STA6543220004" ,
                "STA6543220005" ,
                "STA6543220006" ,
                "STA6543220007" ,
                "STA6543220008" ,
                "STA6543220009" ,
                "STA6543220010" ,
                "STA6543220011" ,
                "STA6543220012" ,
                "STA6543220013" ,
                "STA6543220014" ,
                "STA6543220015" ,
                "STA6543220016" ,
                "STA6543220017" ,
                "STA6543220018" ,
                "STA6543220019" ,
                "STA6543220020" ,
                "STA6543220021" ,
                "STA6543220022" ,
                "STA6543220023" ,
                "STA6543220024" ,
                "STA6543220025" ,
                "STA6543220026" ,
                "STA6543220027" ,
                "STA6543220028" ,
                "STA6543220029" ,
                "STA6543220030" ,
                "STA6543220031" ,
                "STA6543220032" ,
                "STA6543220033" ,
                "STA6543220034" ,
                "STA6543220035" ,
                "STA6543220036" ,
                "STA6543220037" ,
                "STA6543220038" ,
                "STA6543220039" ,
                "STA6543220040" ,
                "STA6543220041" ,
                "STA6543220042" ,
                "STA6543220043" ,
                "STA6543220044" ,
                "STA6543220045" ,
                "STA6543220046" ,
                "STA6543220047" ,
                "STA6543220048" ,
                "STA6543220049" ,
                "STA6543220050" ,
                "STA6543220051" ,
                "STA6543220052" ,
                "STA6543220053" ,
                "STA6543220054" ,
                "STA6543220055" ,
                "STA6543220056" ,
                "STA6543220057" ,
                "STA6543220058" ,
                "STA6543220059" ,
                "STA6543220060" ,
                "STA6543220061" ,
                "STA6543220062" ,
                "STA6543220063" ,
                "STA6543220064" ,
                "STA6543220065" ,
                "STA6543220066" ,
                "STA6543220067" ,
                "STA6543220068" ,
                "STA6543220069" ,
                "STA6543220070" ,
                "STA6543220071" ,
                "STA6543220072" ,
                "STA6543220073" ,
                "STA6543220074" ,
                "STA6543220075" ,
                "STA6543220076" ,
                "STA6543220077" ,
                "STA6543220078" ,
                "STA6543220079" ,
                "STA6543220080" ,
                "STA6543220081," ,
                "STA6543220082," ,
                "STA6543220083," ,
                "STA6543220084," ,
                "STA6543220085," ,
                "STA6543220086," ,
                "STA6543220087," ,
                "STA6543220088," ,
                "STA6543220089," ,
                "STA6543220090," ,
                "STA6543220091," ,
                "STA6543220092," ,
                "STA6543220093," ,
                "STA6543220094," ,
                "STA6543220095," ,
                "STA6543220096," ,
                "STA6543220097," ,
                "STA6543220098," ,
                "STA6543220099," ,
                "STA6543220100," ,
                "STA6543220101," ,
                "STA6543220102," ,
                "STA6543220103," ,
                "STA6543220104," ,
                "STA6543220105," ,
                "STA6543220106," ,
                "STA6543220107," ,
                "STA6543220108," ,
                "STA6543220109," ,
                "STA6543220110," ,
                "STA6543220111," ,
                "STA6543220112," ,
                "STA6543220113," ,
                "STA6543220114," ,
                "STA6543220115," ,
                "STA6543220116," ,
                "STA6543220117," ,
                "STA6543220118," ,
                "STA6543220119," ,
                "STA6543220120," ,
                "STA6543220121," ,
                "STA6543220122," ,
                "STA6543220123," ,
                "STA6543220124," ,
                "STA6543220125," ,
                "STA6543220126"};
        for (int i = 0; i <statCds.length ; i++) {
            System.out.println(statCds[i]);
        }

    }
}
